<?php
require_once('../includes/init.php');
require(ROOT_PATH . '/includes/lib_array.php');
require(ROOT_PATH . '/includes/lib_attribute.php');
require(TMP_PATH . '/config/cfg_product_cate_new.php');
require(TMP_PATH . '/config/cfg_product_bigcate.php');
require(TMP_PATH . '/config/cfg_standard_cate.php');
$domain = "https://www.pentalink.com";
?>
<?php include('./header.php');?>
<?php
$sql = "SELECT count(*) FROM `cart` WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
$cart_sum = $db->getOne($sql);

$sql = "SELECT *,if(`sort_order` > '0',1,0) AS `is_order` FROM `product_cate` WHERE `parent_id`='0' AND `is_index`='1' AND `is_del`='0' AND `bigcate_id`='1' ORDER BY `is_order` DESC, `sort_order`;";
$cate_list = $db->getAll($sql);


$cateId = $_GET["cate_id"];
$cate_id = $cateId;
if(empty($cateId)){
    $cateId = 0;
}
$page = $_GET["page"];
if(empty($page)){
    $page = 1;
}
$page_size = $_GET["page_size"];
if(empty($page_size)){
    $page_size = 8;
}

$parentCate = false;
$cateInfo = $db->getRow("select * from `product_cate` where `cate_id` = $cateId");
if(empty($cateInfo)){
    $cateInfo["cate_name"] = "全部分类";
}else{
    if($cateInfo["parent_id"] > 0){
        $parentCate = $db->getRow("select * from `product_cate` where `cate_id` = " . $cateInfo["parent_id"]);
    }
}

$offset = ($page-1) * $page_size;

$conditions = "`is_show`='1' AND `is_del`='0'";
if(!empty($cateId) && $cateId > 0){
    $conditions .= "  AND LOCATE(CONCAT(',', '".$cateId."', ','), CONCAT(',', cate_ids, ','))";
}

/**
 * 规格筛选，地址处理
 */
function ck_url($params, $cid='')
{
    //基础地址
    if($cid<>'')
    {
        $params['cate_id'] = $cid;
    }
    if($params['cate_id']) $url = 'product.php?cate_id='.$params['cate_id'];
    else  $url = 'product.php';
    unset($params['cate_id']);

    //$url = 'list.php';
    //属性都以a开头，a+父类id=子类id
    $params = array_filter($params, 'strlen');

    //unset($params['cate_id']);
    if (!empty($params))
    {
        $url .= '&' . http_build_query($params, '', '&');
    }
    return $url;
}

function sel_params($params, $has_a=true)
{
    $res_arr = array();
    if(empty($params))
    {
        //die("a");
        return array();
    }
    else
    {
        //die("b");
        foreach($params as $key => $val)
        {
            //echo $key;
            if(preg_match('/^a(\d{1,5})/i', $key, $m))
            {
                //die("a");
                //print_r($m);
                $k = $has_a ? $key : $m[1];
                $res_arr[$k] = $val;
            }
        }
    }
    return $res_arr;
}

$attr_arr = sel_params($_GET, false);
if(!empty($attr_arr))
{
    //通过属性表product_attr反查哪些id有这个属性值
    //$attr_ids = array_unique(array_keys($attr_arr));
    $attr_vals = array_unique(array_values($attr_arr));
    $val_num=count($attr_vals);
    $sql_pid="SELECT `product_id`,count(*) AS vn FROM `product_attr` 
			WHERE `attr_value` ".db_create_in($attr_vals)." AND LOCATE(CONCAT(',', '".$cate_id."', ','), CONCAT(',', cate_ids, ',')) 
			GROUP BY `product_id` HAVING vn>={$val_num}";
    $arr_pid = $db->getAll($sql_pid);
    $plistArr = array();
    $plistArr[] = 0;
    foreach($arr_pid AS $key => $pArr)
    {
        $plistArr[] = $pArr['product_id'];
    }


    //$conditions .= " AND `product_id` IN (SELECT DISTINCT `product_id` FROM `product_attr` WHERE `attr_value` ".db_create_in($attr_vals).")";
    $conditions .= " AND `product_id` IN (".implode(",",$plistArr).")";

}

//关键字搜索，TODO 改进为sphinx的自动分词，全索引搜索
//$keyword = trim(urldecode($_POST['keyword']));
$keywordinfo = $keyword = trim($_REQUEST['keyword']);
//可以被过滤的代码或文字
$filerArr=array("/DIN/si","/ASNI/si","/ASME/si","/JB/si","/JIS/si","/GB/si","/\/t/si","/GB( T){1}/si");
$keyword=preg_replace($filerArr, "", $keyword);

if(is_numeric($keyword)) $conditions .= " AND `search_info` LIKE '%,".$keyword.",%'";
elseif($keyword<>'')
{
  $keywordArr = explode(" ",$keyword);
  foreach($keywordArr AS $k => $v) {
    $conditions .= " AND `search_info` LIKE '%".$v."%'";
  }
}


$sql = "SELECT *,if(`sort_order` > '0',1,0) AS `is_order` FROM `product` WHERE ".$conditions." ORDER BY  `is_order` DESC,`sort_order`, `add_tm` DESC, `product_id` DESC LIMIT $page_size offset $offset";
$product_list = $db->getAll($sql);

$sql1 = "SELECT count(*) FROM `product` WHERE ".$conditions.";";
$totalCount = $db->getOne($sql1);

$totalCount = $totalCount;
$data = array(
    'totalCount'	=> $totalCount,
    'pageSize'		=> $page_size,
    'currentPage'	=> $page
);
$pageCount = ceil($totalCount/$pageSize);
$pager = create_pages_new($data, $_GET, true);

$_GET["from_page"] = "product";


//读取数量
$sql = "SELECT `cate_id`,`parent_id`,`product_num`,`x_attr_name`,`y_attr_name` FROM `product_cate` WHERE 1";
$cateNum = $db->getAll($sql);
foreach($cateNum AS $key => $cateNum)
{
    $cateNumArr[$cateNum['cate_id']] = $cateNum['product_num'];
    if($cateNum['parent_id']) $cateParentidArr[$cateNum['cate_id']] = $cateNum['parent_id'];
    $xy_attrArr['x'][$cateNum['cate_id']] = $cateNum['x_attr_name'];
    $xy_attrArr['y'][$cateNum['cate_id']] = $cateNum['y_attr_name'];
}

if($cate_id)
{
    //读取分类信息
    $sql = "SELECT * FROM `product_cate` WHERE `cate_id`='".$cate_id."';";
    $cate = $db->getRow($sql);
    //处理分类
    $cate_arr = explode(',', $cate['parent_list']);
    //大类
    //$bigcate = $cate['bigcate_id']<>''?$cate['bigcate_id']:'1';


    //左侧循环一级分类
    $cate1_id = $cate_arr[0]=='0'?$cate_id:$cate_arr[0];
    //若是一级分类就用一级分类的第一个子类，展开
    $left_open = current(array_keys($cfg_product_cate['b'.$bigcate][$cate1_id]));
    if(count($cate_arr)==1&&$cate_arr[0]<>'0')
    {
        $cate2_id = $cate_id;
        $cate3_id = '';
        $left_open = $cate2_id;
    }
    if(count($cate_arr)==2)
    {
        $cate2_id = $cate_arr[1];
        $cate3_id = $cate_id;
        $left_open = $cate2_id;
    }
    //左侧顶部
    //$left_name = $cfg_product_cate['b'.$bigcate]['0'][$cate1_id];
    //左侧循环开始分类
    //$left_cate1_id = $cate1_id;

    if($bigcate<>'1' || 1)
    {
        $left_cate1_id = 0;
        $left_open = $cate['parent_id']==0?$cate_id:$cate_arr[0];
        $left_name = $cfg_product_bigcate[$bigcate];
    }
}
else
{
    //$bigcate = 1;
    $left_cate1_id = 0;
    $left_name = '按分类查找';
}
?>
            <!-- 头部搜索框以及导航栏 -->
            <div class="header_div">
                <?php include('./common/search.php');?>
                <?php include('./common/nav.php');?>
            </div>
 
            <!-- 标签 -->
            <div class="post_position" style="position: sticky;top: 178px;background: #f5f5f5;z-index: 999;">
                <span class="home_span"><a href="./index.php">首页 > </a></span>
                <?php if($parentCate):?>
                <span><a href="./product.php?cate_id=<?php echo $parentCate["cate_id"]; ?>"><?php echo $parentCate["cate_name"]; ?> > </a></span>
                <?php endif;?>
                <span><a><?php echo $cateInfo["cate_name"]; ?></a></span>
            </div>

            <div class="proList_content">
                <div class="proList_content_left box" style="position: fixed;top: 226px;">
                    <h1>选型指南</h1>
                    <div class="delete box"><a href="./product.php?cate_id=<?php echo $cateId; ?>">清除条件</a></div>

                    <!-- 开始 -->
                    <?php if($cateInfo["cate_name"] != "全部分类"): ?>
                        <?php
                            $attr_list = attr_sel_list1(0, $cate_id,$productlistidArr, true);
                            if (!empty($attr_list)):
                        ?>

                                <?php
                                 foreach ($attr_list as $attr):
                                ?>
                                    <?php if ($attr['attr_id'] <> 50): ?>
                                        <?php
                                            $i = 1;
                                            $attr2_list = attr_sel_list1($attr['attr_id'], $cate_id,$productlistidArr, true, false);
                                            $sel1 = 0;
                                            foreach ($attr2_list as $attr2) {
                                                if($sel1!=1){
                                                    $sel1 = $_GET['a' . $attr['attr_id']] == $attr2['attr_id'] ? '1' : '0';
                                                }
                                            }
                                    ?>

                                        <div  class="condition_block box">
                                            <h2><?php echo $attr['attr_name'] ?></h2>
                                            <ul class="box">
                                                <?php
                                                $x_num = count($attr2_list);
                                                if (!empty($attr2_list)):
                                                ?>
                                                    <?php 
                                                        foreach ($attr2_list as $key=>$attr2):
                                                            //判断当前的是否选中
                                                            $sel = $_GET['a' . $attr['attr_id']] == $attr2['attr_id'] ? '1' : '0';
                                                            //get参数处理
                                                            $params = $_GET;
                                                            if ($sel == '1') {
                                                                unset($params['a' . $attr['attr_id']]);
                                                                unset($params[$attr['pinyin']]);
                                                                unset($params[$attr['attr_name']]);
                                                            } else {
                                                                $params['a' . $attr['attr_id']] = $attr2['attr_id'];
                                                                if ($attr['pinyin'] <> '' && $attr2['pinyin'] <> '') {
                                                                    $params[$attr['pinyin']] = $attr2['pinyin'];
                                                                    $params[$attr['attr_name']] = $attr2['short_name'] == '' ? $attr2['attr_name'] : $attr2['short_name'];
                                                                }else{
                                                                    $params[$attr['attr_name']] = $attr2['short_name'] == '' ? $attr2['attr_name'] : $attr2['short_name'];
                                                                }
                                                            }
                                                    ?>
                                                        <li>
                                                            <a href="<?php echo ck_url($params); ?>"  <?php if ($sel == '1'): ?> style="color: #E90211" <?php endif; ?>>
                                                                <?php echo $attr2['short_name'] == '' ? $attr2['attr_name'] : $attr2['short_name']; ?>
                                                            </a>
                                                        </li>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                                    
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                               
                        <?php endif; ?>
                    <!-- 结束 -->
                    <?php endif; ?>
                </div>
                <div class="proList_content_right box">
                    <div class="proList_fenlei_block box">
                        <h1>商品分类</h1>
                        <ul>
                                <?php
                                if(!empty($cate_list)):
                                foreach($cate_list as $key1 => $cate1):  
                                ?>
                                    <li class="box">
                                        <a href="./product.php?cate_id=<?php echo $cate1['cate_id']; ?>">
                                            <img src="/upload<?php echo $cate1['pic']<>''?$cate1['pic']:'/none.jpg';?>" alt="<?php echo $cate1['cate_name'];?>">
                                            <p><?php echo $cate1['cate_name'];?></p>
                                        </a>
                                    </li>
                                <?php endforeach;?>
                                <?php endif;?>
                        </ul>
                    </div>
                    <div class="product_list_info box">
                        <div class="product_list_top box">
                            <h1 class="fl">产品列表</h1>
                            <p class="fl fl_number">共<span><?php echo $totalCount; ?></span>件商品</p>
                        </div>
                        <!-- 选中列表 -->
                        <div class="list_tabel_block box">
                            <div class="tabel_content box">
                                <!-- 橱窗ul -->
                                <ul class="chuchuang_ul" style="display: block">
                                    <?php
                                    foreach($product_list as $pk => $product):
                                        $sql = "SELECT *,if(`sort_order` > '0',1,0) AS `is_order` FROM `product_pic` WHERE `product_id`='".$product['product_id']."' AND `ftype`=1 ORDER BY `is_order` DESC, `sort_order` LIMIT 1;";
                                        $pic = $db->getRow($sql);

                                        $gg_num = 0;

                                        $sql1 = "SELECT count(*) FROM `product_detail` WHERE `product_id`='".$product['product_id']."' AND `is_show`='1' AND `is_del`='0'";
                                        $sql1 .= " ORDER BY `pd_id`;";
                                        $gg_num = $db->getOne($sql1);
                                        // $cate_arr = explode(',', $product['cate_ids']);
                                        // if($cateId == 0){
                                        //     $cateId = $cate_arr[0];
                                        // }
                                    ?>
                                        <li class="box">
                                            <a href="./proDetail.php?id=<?php echo $product["product_id"]; ?>&cate_id=<?php echo $cateId; ?>">
                                                <div class="linjian_img">
                                                    <img src="<?php echo $domain; ?>/upload<?php echo $pic["pic400"]; ?>" alt="<?php echo $product["title"]; ?>">
                                                </div>
                                                <!-- <p class="ellipsis">三联式组合件 安装</p> -->
                                                <p class="ellipsis"><?php echo $product["title"]; ?></p>
                                                <div class="xuanze_number">共计<?php echo $gg_num;?>种规格可选</div>
                                            </a>
                                        </li>
                                    <?php endforeach;?>
                                </ul>

                                <!-- 分页开始 -->
                                
                                <div class="tcdPageCode">
                                    <?php echo $pager;?>
                                    <!-- <a href="/" class="one_end">首页</a>
                                    <span class="disabled_l">上一页</span>
                                    <span class="current">1</span>
                                    <a href="#" class="tcdNumber">2</a>
                                    <a href="#" class="tcdNumber">3</a>
                                    <a href="#" class="tcdNumber">4</a>
                                    <span class="pageCount">...</span>
                                    <a href="#" class="tcdNumber">50</a>
                                    <a href="#" class="nextPage">下一页</a>
                                    <a href="/" class="one_end">尾页</a> -->
                                </div>
                                <!-- 分页结束 -->
                            </div>
                        </div>

                  
                    </div>
                </div>
            </div>

<?php include('./footer.php');?>